<template>
  <el-dialog title="批量修改" :visible.sync="visible" width="500px" @close="handleClose">
    <el-form :model="form" label-width="80px">
      <el-form-item label="修改项:">
        <el-select v-model="form.editField" placeholder="请选择" style="width: 100%">
          <el-option label="负责人" value="staff_id" />
          <el-option label="产品名称/类别" value="productName" />
          <el-option label="批次" value="batch" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="修改方式:">
        <el-select v-model="form.editMethod" placeholder="请选择" style="width: 100%">
          <el-option label="修改成新的" value="replace" />
          <el-option label="清空现有" value="clear" />
        </el-select>
      </el-form-item>
      
      <!-- 修改内容 -->
      <el-form-item label="修改内容:" v-if="form.editMethod !== 'clear'">
        <!-- 负责人选择 -->
        <div v-if="form.editField === 'staff_id'" style="width: 100%" @click="openUserSelect">
          <el-input v-model="form.staffName" placeholder="请选择负责人" readonly style="width: 100%; cursor: pointer" />
        </div>
        
        <!-- 产品名称选择 -->
        <el-select
          v-else-if="form.editField === 'productName'"
          v-model="form.productName"
          placeholder="请选择产品名称/类别"
          style="width: 100%"
        >
          <el-option 
            v-for="product in productOptions" 
            :key="product.id" 
            :label="product.name" 
            :value="product.name" 
          />
        </el-select>
        
        <!-- 批次输入 -->
        <el-input
          v-else-if="form.editField === 'batch'"
          v-model="form.batch"
          placeholder="请输入批次"
          style="width: 100%"
        />
        
        <!-- 默认输入框 -->
        <el-input
          v-else
          v-model="form.editValue"
          :placeholder="`请输入${getFieldLabel(form.editField)}`"
          style="width: 100%"
        />
      </el-form-item>
      
      <!-- 清空提示 -->
      <el-form-item v-if="form.editMethod === 'clear'" label="修改内容:">
        <div style="color: #909399; font-style: italic;">
          将清空选中客户的{{ getFieldLabel(form.editField) }}字段内容
        </div>
      </el-form-item>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <div style="display: flex; justify-content: space-between; width: 100%;">
        <el-button type="primary" @click="handleBatchEdit">批量修改</el-button>
        <el-button @click="handleModifyAll">全部修改（{{total}}条）</el-button>
      </div>
    </div>
    
    <!-- 负责人选择弹窗 -->
    <user-radio-dialog :visible.sync="userSelectVisible" @confirm="handleUserSelect" />
  </el-dialog>
</template>

<script>
import UserRadioDialog from '@/components/UserRadioDialog.vue'
import { departmentList } from '@/api/setting/role'

export default {
  name: 'BatchEditDialog',
  components: {
    UserRadioDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    productOptions: {
      type: Array,
      default: () => []
    },
    selectedCount: {
      type: Number,
      default: 0
    },
    total: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      form: {
        editField: '',
        editMethod: 'replace',
        editValue: '',
        staff_id: '',
        staffName: '',
        productName: '',
        batch: ''
      },
      departments: [],
      userSelectVisible: false
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.loadDepartments()
        this.resetForm()
      }
    }
  },
  methods: {
    async loadDepartments() {
      try {
        const res = await departmentList()
        if (res.code === 1 && res.data && res.data.tree) {
          this.departments = res.data.tree
        }
      } catch (error) {
        console.error('加载部门列表失败:', error)
      }
    },
    
    resetForm() {
      this.form = {
        editField: '',
        editMethod: 'replace',
        editValue: '',
        staff_id: '',
        staffName: '',
        productName: '',
        batch: ''
      }
    },
    
    openUserSelect() {
      this.userSelectVisible = true
    },
    
    handleUserSelect(users) {
      if (users && users.length > 0) {
        this.form.staff_id = users[0].id
        this.form.staffName = users[0].name
      }
      this.userSelectVisible = false
    },
    
    handleClose() {
      this.$emit('update:visible', false)
    },
    
    // 批量修改方法
    handleBatchEdit() {
      if (this.selectedCount === 0) {
        this.$message.warning('请选中数据')
        return
      }
      
      if (!this.form.editField) {
        this.$message.warning('请选择要修改的项')
        return
      }
      
      if (!this.form.editMethod) {
        this.$message.warning('请选择修改方式')
        return
      }
      
      // 如果选择清空现有，不需要验证输入内容
      if (this.form.editMethod === 'clear') {
        this.$emit('confirm', this.buildEditData())
        this.handleClose()
        return
      }
      
      // 验证修改内容
      if (!this.hasValidContent()) {
        return
      }
      
      this.$emit('confirm', this.buildEditData())
      this.handleClose()
    },
    
    // 全部修改方法
    handleModifyAll() {
      if (!this.form.editField) {
        this.$message.warning('请选择要修改的项')
        return
      }
      
      if (!this.form.editMethod) {
        this.$message.warning('请选择修改方式')
        return
      }
      
      // 如果选择清空现有，不需要验证输入内容
      if (this.form.editMethod === 'clear') {
        this.$emit('modify-all', this.buildEditData())
        this.handleClose()
        return
      }
      
      // 验证修改内容
      if (!this.hasValidContent()) {
        return
      }
      
      this.$emit('modify-all', this.buildEditData())
      this.handleClose()
    },
    
    // 构建编辑数据
    buildEditData() {
      const editData = {
        editField: this.form.editField,
        editMethod: this.form.editMethod
      }
      
      // 根据字段类型添加对应的值
      switch (this.form.editField) {
        case 'staff_id':
          editData.staff_id = this.form.staff_id
          break
          
        case 'productName':
          editData.productName = this.form.productName
          break
          
        case 'batch':
          editData.batch = this.form.batch
          break
          
        default:
          editData[this.form.editField] = this.form.editValue
          break
      }
      
      return editData
    },
    
    // 验证修改内容
    hasValidContent() {
      switch (this.form.editField) {
        case 'staff_id':
          if (!this.form.staff_id) {
            this.$message.warning('请选择负责人')
            return false
          }
          break
          
        case 'productName':
          if (!this.form.productName) {
            this.$message.warning('请选择产品名称/类别')
            return false
          }
          break
          
        case 'batch':
          if (!this.form.batch.trim()) {
            this.$message.warning('请输入批次')
            return false
          }
          break
          
        default:
          if (!this.form.editValue.trim()) {
            this.$message.warning('请输入修改内容')
            return false
          }
          break
      }
      return true
    },

    // 根据修改项获取标签文本
    getFieldLabel(field) {
      switch (field) {
        case 'staff_id':
          return '负责人'
        case 'productName':
          return '产品名称/类别'
        case 'batch':
          return '批次'
        default:
          return ''
      }
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 